package cn.schoolwow.ams.module.block.listBlock.clazzBlock.initial.flow.field;

import cn.schoolwow.ams.domain.block.list.common.AMSFieldOption;
import cn.schoolwow.quickdao.annotation.Ignore;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.dto.FlowContextDataRange;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.reflection.FieldFilter;
import cn.schoolwow.util.domain.query.reflection.QueryReflection;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.List;

public class SetClazzListBlockFieldsFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        Class entityClass = (Class) flowContext.checkData("entityClass");
        String[] fieldNames = (String[]) flowContext.getData("fieldNames");

        List<Field> entityFieldList = QueryReflection.newQuery(entityClass)
                .addQuery(fieldNames)
                .addQuery(new FieldFilter() {
                    @Override
                    public boolean filterField(Field field) {
                        if(Modifier.isTransient(field.getModifiers())){
                            return false;
                        }
                        if(null!=field.getAnnotation(Ignore.class)){
                            return false;
                        }
                        return true;
                    }
                })
                .execute()
                .getFieldList();
        if(null==fieldNames||fieldNames.length==0){
            for(Field entityField:entityFieldList){
                addAMSFieldOption(entityField, flowContext);
            }
        }else{
            for(String fieldName:fieldNames){
                for(Field entityField:entityFieldList){
                    if(entityField.getName().equalsIgnoreCase(fieldName)){
                        addAMSFieldOption(entityField, flowContext);
                        break;
                    }
                }
            }
        }
    }

    @Override
    public String name() {
        return "设置ClazzBlock字段列表通用流程";
    }

    private void addAMSFieldOption(Field entityField, FlowContext flowContext){
        List<AMSFieldOption> amsFieldOptionList = (List<AMSFieldOption>) flowContext.getData("amsFieldOptionList");

        AMSFieldOption amsFieldOption = new AMSFieldOption();
        amsFieldOption.name = entityField.getName();
        amsFieldOption.entityField = entityField;
        amsFieldOptionList.add(amsFieldOption);

        flowContext.startFlow(new InitialClazzListBlockFieldOptionFlow())
                .putTemporaryInstanceData(amsFieldOption)
                .execute();
    }
}
